import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { App } from "vue";
import store from "../store";
import Cookies from "js-cookie";
import { getAdminInfoApi } from "../request/api";
const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/login/login.vue')
    },
    {
        path: '/homepage',
        name: 'homepage',
        component: () => import('../views/homepage/homepage.vue')
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    // 路由配置
    routes
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
    // token存在并且menus里面为空数组
    const token = Cookies.get('token')
    if (token && store.state.menus.length == 0) {
        console.log('刷新后,menus为空,重新获取数据');
        // getAdminInfoApi().then(res => {
        //     if (res.code == 200) {
        //         store.commit('updateMenus', res.data.menus)
        //         console.log(store.state.menus);
        //     }
        // })
        store.dispatch('getAdminInfo')
    }
    next()
})

export const initRouter = (app: App<Element>) => {
    app.use(router)
}